<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航 -->
    <nav class="h-24 bg-white shadow-sm fixed w-full z-50 flex items-center justify-between px-8">
      <div class="flex items-center gap-8">
        <!-- EduLiveLink Logo -->
        <div class="flex items-center gap-4 bg-slate-800 px-5 py-3 rounded-lg">
          <div class="logo-icon w-12 h-12">
            <svg viewBox="0 0 100 100" fill="none">
              <circle cx="50" cy="50" r="45" stroke="url(#gradient1)" stroke-width="3" fill="none"/>
              <circle cx="50" cy="50" r="35" stroke="url(#gradient2)" stroke-width="2" fill="none"/>
              <path d="M30 40 L50 30 L70 40 L70 60 L50 70 L30 60 Z" fill="url(#gradient3)" opacity="0.8"/>
              <circle cx="50" cy="50" r="8" fill="white"/>
              <defs>
                <linearGradient id="gradient1" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#4A90E2"/>
                  <stop offset="100%" style="stop-color:#7BB3F0"/>
                </linearGradient>
                <linearGradient id="gradient2" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#5BA0F2"/>
                  <stop offset="100%" style="stop-color:#8CC8FF"/>
                </linearGradient>
                <linearGradient id="gradient3" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#4A90E2"/>
                  <stop offset="100%" style="stop-color:#6BB0FF"/>
                </linearGradient>
              </defs>
            </svg>
          </div>
          <div class="flex flex-col">
            <span class="text-xl font-bold text-blue-600">
              EduLiveLink
            </span>
            <span class="text-xs text-black">
              智能教育平台
            </span>
          </div>
        </div>
        
        <div class="flex gap-8">
          <router-link to="/home" class="text-gray-600 hover:text-blue-600 transition-colors text-base font-medium">首页</router-link>
          <router-link to="/courses" class="text-gray-600 hover:text-blue-600 transition-colors text-base font-medium">课程</router-link>
          <router-link to="/classes" class="text-blue-600 font-semibold text-base">班级管理</router-link>
          <router-link to="/resources" class="text-gray-600 hover:text-blue-600 transition-colors text-base font-medium">资源</router-link>
        </div>
      </div>
      <div class="flex items-center gap-4">
        <el-button type="primary" size="default" class="rounded px-6 font-medium" @click="goHome">返回首页</el-button>
      </div>
    </nav>

    <!-- 上方空白区域 -->
    <div class="h-32 bg-white"></div>

    <!-- 主要内容区域 -->
    <div class="container mx-auto px-8 py-8">
      <!-- 页面标题和操作按钮 -->
      <div class="flex justify-between items-start mb-8">
        <div>
          <h1 class="text-3xl font-bold text-gray-900 mb-2">班级列表</h1>
          <p class="text-gray-600">管理和查看所有班级信息</p>
        </div>
        <div class="flex gap-4">
          <el-button 
            type="info" 
            size="large" 
            class="flex items-center gap-2"
            @click="exportData"
            :loading="exporting"
          >
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button 
            type="primary" 
            size="large" 
            class="flex items-center gap-2"
            @click="showCreateDialog = true"
          >
            <el-icon><Plus /></el-icon>
            新增班级
          </el-button>
        </div>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">搜索</label>
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索班级名称或班主任"
              class="w-full"
              :prefix-icon="Search"
              clearable
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">年级</label>
            <el-select v-model="searchForm.grade" placeholder="所有年级" class="w-full" clearable>
              <el-option
                v-for="grade in gradeOptions"
                :key="grade.value"
                :label="grade.label"
                :value="grade.value"
              />
            </el-select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
            <el-select v-model="searchForm.status" placeholder="所有状态" class="w-full" clearable>
              <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </div>
          <div class="flex gap-3">
            <el-button type="primary" @click="searchClasses" :loading="loading">
              搜索
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
        </div>
      </div>

      <!-- 班级列表表格 -->
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-4 text-left">
                  <el-checkbox 
                    v-model="selectAll" 
                    @change="handleSelectAll"
                    :indeterminate="isIndeterminate"
                  />
                </th>
                <th class="px-6 py-4 text-left text-sm font-medium text-gray-900">班级名称</th>
                <th class="px-6 py-4 text-left text-sm font-medium text-gray-900">年级</th>
                <th class="px-6 py-4 text-left text-sm font-medium text-gray-900">班主任</th>
                <th class="px-6 py-4 text-left text-sm font-medium text-gray-900">学生数量</th>
                <th class="px-6 py-4 text-left text-sm font-medium text-gray-900">成立日期</th>
                <th class="px-6 py-4 text-left text-sm font-medium text-gray-900">状态</th>
                <th class="px-6 py-4 text-left text-sm font-medium text-gray-900">操作</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-200">
              <tr v-for="classItem in classList" :key="classItem.id" class="hover:bg-gray-50">
                <td class="px-6 py-4">
                  <el-checkbox 
                    v-model="classItem.selected" 
                    @change="handleSelectChange"
                  />
                </td>
                <td class="px-6 py-4">
                  <div class="flex items-center gap-3">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                      {{ classItem.classCode }}
                    </span>
                    <span class="text-sm font-medium text-gray-900">{{ classItem.className }}</span>
                  </div>
                </td>
                <td class="px-6 py-4 text-sm text-gray-900">{{ classItem.grade }}</td>
                <td class="px-6 py-4">
                  <div class="flex items-center gap-3">
                    <el-avatar :size="32" :src="classItem.teacherAvatar">
                      {{ classItem.teacherName?.charAt(0) }}
                    </el-avatar>
                    <span class="text-sm text-gray-900">{{ classItem.teacherName }}</span>
                  </div>
                </td>
                <td class="px-6 py-4 text-sm text-gray-900">{{ classItem.studentCount }}</td>
                <td class="px-6 py-4 text-sm text-gray-900">{{ classItem.establishDate }}</td>
                <td class="px-6 py-4">
                  <span 
                    :class="getStatusClass(classItem.status)"
                    class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                  >
                    {{ getStatusText(classItem.status) }}
                  </span>
                </td>
                <td class="px-6 py-4">
                  <div class="flex items-center gap-2">
                    <el-button 
                      type="primary" 
                      size="small" 
                      text
                      @click="viewClass(classItem)"
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                    <el-button 
                      type="warning" 
                      size="small" 
                      text
                      @click="editClass(classItem)"
                    >
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button 
                      type="danger" 
                      size="small" 
                      text
                      @click="deleteClass(classItem)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="bg-white px-6 py-4 border-t border-gray-200 flex items-center justify-between">
          <div class="text-sm text-gray-700">
            显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, total) }} 条，共 {{ total }} 条记录
          </div>
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新增/编辑班级弹窗 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingClass ? '编辑班级' : '新增班级'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="classFormRef"
        :model="classForm"
        :rules="classFormRules"
        label-width="100px"
      >
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="classForm.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="classForm.grade" placeholder="请选择年级" class="w-full">
            <el-option
              v-for="grade in gradeOptions"
              :key="grade.value"
              :label="grade.label"
              :value="grade.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班主任" prop="teacherName">
          <el-input v-model="classForm.teacherName" placeholder="请输入班主任姓名" />
        </el-form-item>
        <el-form-item label="成立日期" prop="establishDate">
          <el-date-picker
            v-model="classForm.establishDate"
            type="date"
            placeholder="选择成立日期"
            class="w-full"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="班级描述" prop="description">
          <el-input
            v-model="classForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入班级描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-3">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="submitClass" :loading="submitting">
            {{ editingClass ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 班级详情弹窗 -->
    <el-dialog
      v-model="showDetailDialog"
      title="班级详情"
      width="800px"
    >
      <div v-if="selectedClass" class="space-y-6">
        <div class="grid grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">班级名称</label>
            <p class="text-gray-900">{{ selectedClass.className }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">年级</label>
            <p class="text-gray-900">{{ selectedClass.grade }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">班主任</label>
            <p class="text-gray-900">{{ selectedClass.teacherName }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">学生数量</label>
            <p class="text-gray-900">{{ selectedClass.studentCount }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">成立日期</label>
            <p class="text-gray-900">{{ selectedClass.establishDate }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
            <span 
              :class="getStatusClass(selectedClass.status)"
              class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
            >
              {{ getStatusText(selectedClass.status) }}
            </span>
          </div>
        </div>
        <div v-if="selectedClass.description">
          <label class="block text-sm font-medium text-gray-700 mb-2">班级描述</label>
          <p class="text-gray-900">{{ selectedClass.description }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
      v-model="showDeleteDialog"
      title="确认删除"
      width="400px"
    >
      <p class="text-gray-700">确定要删除班级 "{{ deletingClass?.className }}" 吗？此操作不可恢复。</p>
      <template #footer>
        <div class="flex justify-end gap-3">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleting">删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Plus, 
  Download, 
  View, 
  Edit, 
  Delete 
} from '@element-plus/icons-vue'
import { 
  getClassList, 
  createClass, 
  updateClass, 
  deleteClass as deleteClassAPI,
  exportClassData 
} from '@/api/class'

// 响应式数据
const loading = ref(false)
const exporting = ref(false)
const submitting = ref(false)
const deleting = ref(false)
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)
const showDeleteDialog = ref(false)
const editingClass = ref(null)
const selectedClass = ref(null)
const deletingClass = ref(null)
const classFormRef = ref(null)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 选择相关
const selectAll = ref(false)
const isIndeterminate = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  grade: '',
  status: ''
})

// 班级表单
const classForm = reactive({
  className: '',
  grade: '',
  teacherName: '',
  establishDate: '',
  description: ''
})

// 班级列表
const classList = ref([])

// 选项数据
const gradeOptions = [
  { value: '一年级', label: '一年级' },
  { value: '二年级', label: '二年级' },
  { value: '三年级', label: '三年级' },
  { value: '四年级', label: '四年级' },
  { value: '五年级', label: '五年级' },
  { value: '六年级', label: '六年级' },
  { value: '初一', label: '初一' },
  { value: '初二', label: '初二' },
  { value: '初三', label: '初三' },
  { value: '高一', label: '高一' },
  { value: '高二', label: '高二' },
  { value: '高三', label: '高三' }
]

const statusOptions = [
  { value: 'active', label: '正常' },
  { value: 'graduated', label: '已毕业' },
  { value: 'inactive', label: '停用' }
]

// 表单验证规则
const classFormRules = {
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  teacherName: [
    { required: true, message: '请输入班主任姓名', trigger: 'blur' }
  ],
  establishDate: [
    { required: true, message: '请选择成立日期', trigger: 'change' }
  ]
}

// 计算属性
const selectedClasses = computed(() => {
  return classList.value.filter(item => item.selected)
})

// 方法
const goHome = () => {
  window.location.href = '/home'
}

const loadClasses = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const response = await getClassList(params)
    classList.value = response.data.map(item => ({
      ...item,
      selected: false
    }))
    total.value = response.total
  } catch (error) {
    ElMessage.error('加载班级列表失败')
  } finally {
    loading.value = false
  }
}

const searchClasses = () => {
  currentPage.value = 1
  loadClasses()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    grade: '',
    status: ''
  })
  currentPage.value = 1
  loadClasses()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadClasses()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadClasses()
}

const handleSelectAll = (val) => {
  classList.value.forEach(item => {
    item.selected = val
  })
  isIndeterminate.value = false
}

const handleSelectChange = () => {
  const selectedCount = selectedClasses.value.length
  const totalCount = classList.value.length
  
  selectAll.value = selectedCount === totalCount
  isIndeterminate.value = selectedCount > 0 && selectedCount < totalCount
}

const viewClass = (classItem) => {
  selectedClass.value = classItem
  showDetailDialog.value = true
}

const editClass = (classItem) => {
  editingClass.value = classItem
  Object.assign(classForm, {
    className: classItem.className,
    grade: classItem.grade,
    teacherName: classItem.teacherName,
    establishDate: classItem.establishDate,
    description: classItem.description || ''
  })
  showCreateDialog.value = true
}

const deleteClass = (classItem) => {
  deletingClass.value = classItem
  showDeleteDialog.value = true
}

const confirmDelete = async () => {
  if (!deletingClass.value) return
  
  deleting.value = true
  try {
    await deleteClassAPI(deletingClass.value.id)
    ElMessage.success('删除成功')
    showDeleteDialog.value = false
    loadClasses()
  } catch (error) {
    ElMessage.error('删除失败')
  } finally {
    deleting.value = false
  }
}

const submitClass = async () => {
  if (!classFormRef.value) return
  
  try {
    await classFormRef.value.validate()
    
    submitting.value = true
    if (editingClass.value) {
      await updateClass(editingClass.value.id, classForm)
      ElMessage.success('更新成功')
    } else {
      await createClass(classForm)
      ElMessage.success('创建成功')
    }
    
    showCreateDialog.value = false
    loadClasses()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  editingClass.value = null
  Object.assign(classForm, {
    className: '',
    grade: '',
    teacherName: '',
    establishDate: '',
    description: ''
  })
  if (classFormRef.value) {
    classFormRef.value.resetFields()
  }
}

const exportData = async () => {
  exporting.value = true
  try {
    const blob = await exportClassData(searchForm)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `班级列表_${new Date().toISOString().split('T')[0]}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

const getStatusClass = (status) => {
  const statusMap = {
    active: 'bg-green-100 text-green-800',
    graduated: 'bg-gray-100 text-gray-800',
    inactive: 'bg-red-100 text-red-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}

const getStatusText = (status) => {
  const statusMap = {
    active: '正常',
    graduated: '已毕业',
    inactive: '停用'
  }
  return statusMap[status] || '未知'
}

// 生命周期
onMounted(() => {
  loadClasses()
})
</script>

<style scoped>
.logo-icon {
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.logo-icon svg {
  width: 100%;
  height: 100%;
}
</style>




